# search.py
# ---------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html

"""
In search.py, you will implement generic search algorithms which are called
by Pacman agents (in searchAgents.py).
"""

import util

class SearchProblem:
    """
    This class outlines the structure of a search problem, but doesn't implement
    any of the methods (in object-oriented terminology: an abstract class).

    You do not need to change anything in this class, ever.
    """

    def getStartState(self):
        """
        Returns the start state for the search problem
        """
        util.raiseNotDefined()

    def isGoalState(self, state):
        """
          state: Search state

        Returns True if and only if the state is a valid goal state
        """
        util.raiseNotDefined()

    def getSuccessors(self, state):
        """
          state: Search state

        For a given state, this should return a list of triples,
        (successor, action, stepCost), where 'successor' is a
        successor to the current state, 'action' is the action
        required to get there, and 'stepCost' is the incremental
        cost of expanding to that successor
        """
        util.raiseNotDefined()

    def getCostOfActions(self, actions):
        """
         actions: A list of actions to take

        This method returns the total cost of a particular sequence of actions.  The sequence must
        be composed of legal moves
        """
        util.raiseNotDefined()


def tinyMazeSearch(problem):
    """
    Returns a sequence of moves that solves tinyMaze.  For any other
    maze, the sequence of moves will be incorrect, so only use this for tinyMaze
    """
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    return  [s,s,w,s,w,w,s,w]

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first

    Your search algorithm needs to return a list of actions that reaches
    the goal.  Make sure to implement a graph search algorithm

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print "Start:", problem.getStartState()
    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    print "Start's successors:", problem.getSuccessors(problem.getStartState())
    """
    "*** YOUR CODE HERE ***"
    currentState=problem.getStartState() 
    if problem.isGoalState(currentState): 
        return []
    else:
        closedSet=set()
        fringe=util.Stack()
        fringe.push((currentState,[]))
        while not fringe.isEmpty():
            currentState,path=fringe.pop()
            #print(path)
            if problem.isGoalState(currentState):
                return path
            elif currentState in closedSet:
                continue       
            else:
                closedSet.add(currentState)
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):                              
                    childNode = (nextState, path + [nextMove])
                    fringe.push(childNode)

def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    currentState=problem.getStartState() 
    if problem.isGoalState(currentState): 
        return []
    else:
        closedSet=set()
        fringe=util.Queue()
        fringe.push((currentState,[]))
        while not fringe.isEmpty():
            currentState,path=fringe.pop()
            #print(path)
            #print "currentState: ", currentState
            if problem.isGoalState(currentState):
                #print(path)
                return path
            elif currentState in closedSet:
                continue       
            else:
                closedSet.add(currentState)
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):                              
                    childNode = (nextState, path + [nextMove])
                    fringe.push(childNode)

def uniformCostSearch(problem):
    "Search the node of least total cost first. "
    "*** YOUR CODE HERE ***"
    currentState=problem.getStartState() 
    if problem.isGoalState(currentState): 
        return []
    else:
        closedSet=set()
        fringe=util.PriorityQueue()
        fringe.push((currentState,[],0),0)
        while not fringe.isEmpty():
            currentState,path,cost=fringe.pop()
            #print(path)
            if problem.isGoalState(currentState):
                return path
            elif currentState in closedSet:
                continue       
            else:
                closedSet.add(currentState)
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):                              
                    childNode = (nextState, path + [nextMove],cost + nextCost)
                    fringe.push(childNode,cost + nextCost)

def nullHeuristic(state, problem=None):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem.  This heuristic is trivial.
    """
    return 0

def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"
    currentState=problem.getStartState() 
    if problem.isGoalState(currentState): 
        return []
    else:
        closedSet=set()
        fringe=util.PriorityQueue()
        fringe.push((currentState,[]),0+heuristic(currentState,problem))
        #print "heuristic: ", heuristic, heuristic(currentState,problem)
        while not fringe.isEmpty():
            currentState,path=fringe.pop()
            #print(path)
            if problem.isGoalState(currentState):
                #print "Path: ", path
                return path
            elif currentState in closedSet:
                continue       
            else:
                closedSet.add(currentState)
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):
                    childNode = (nextState, path + [nextMove])
                    fringe.push(childNode, problem.getCostOfActions(path + [nextMove]) + heuristic(nextState,problem))

def genericSearchFringed(problem, fringe, searchtype, heuristicValue=(lambda x:0)):
    """
    Generic search method
    """
    gameState = problem.getStartState() 
    currentState=gameState
    if problem.isGoalState(currentState):
        return []
    else:
        closedSet=set()
        node = (currentState,[])
        if searchtype == 2:
            fringe.push(node,0+heuristicValue(currentState))
        else:
            fringe.push(node)
        while not fringe.isEmpty():
            currentState,path=fringe.pop()
            if problem.isGoalState(currentState):
                return path
            elif currentState in closedSet:
                continue       
            else:
                closedSet.add(currentState)
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):
                    childNode = (nextState, path + [nextMove])
                    if searchtype == 2:
                        fringe.push(childNode,problem.getCostOfActions(path + [nextMove]) + heuristicValue(nextState))
                    else:
                        fringe.push(childNode)

def genericSearch(problem, fringe, searchtype, heuristicValue=(lambda x:0)):
    """
    Generic search method
    """
    gameState = problem.getStartState()
    currentState=gameState
    linkedList = {(currentState):({},None,currentState,None,0,0)}
    if problem.isGoalState(currentState):
        return []
    else:
        closedSet=set()
        node = currentState
        if searchtype == 2:
            fringe.push(node,0+heuristicValue(currentState))
        else:
            fringe.push(node)
        while not fringe.isEmpty():
            currentState=fringe.pop()
            if problem.isGoalState(currentState):
                path = pathBuilder(linkedList,currentState,[])
                path.reverse()
                return path
            elif currentState in closedSet:
                continue       
            else:
                closedSet.add(currentState)
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):
                    cumulativeCost = nextCost+heuristicValue(nextState)
                    linkedList[nextState] = ({(currentState):linkedList[currentState]},currentState,nextState,nextMove,cumulativeCost,nextCost)
                    if searchtype == 2:
                        fringe.push(nextState,cumulativeCost)
                    else:
                        fringe.push(nextState)

def pathBuilder(linkedList, node, path):
    if node in linkedList:
        (childList,parent,nextState,action,cumulativeCost,nextCost) = linkedList.pop(node)
        if action <> None:
            path.append(action)
        pathBuilder(childList, parent, path)
    else:
        return path
    return path

def genericSearchOld(problem, fringe, searchtype, heuristicValue=(lambda x:0)):
    """
    Generic search method
    """
    gameState = problem.getStartState()
    currentState=gameState
    linkedIndex = 0
    parentIndex = linkedIndex
    node = (currentState, 'SStart', 0, 0, 0, 0)
    linkedList = {(linkedIndex):node}
    if problem.isGoalState(currentState):
        return []
    else:
        closedSet=set()
        if searchtype == 2:
            fringe.push(currentState,0+heuristicValue(currentState))
        else:
            fringe.push(currentState)
        while not fringe.isEmpty():
            currentState=fringe.pop()
            if problem.isGoalState(currentState):
                node = (currentState, linkedList[linkedIndex][1], linkedList[linkedIndex][-4], linkedList[linkedIndex][-3], linkedIndex, linkedList[linkedIndex][-1])
                print "node: ", node, "List: ", linkedList
                path = pathBuilderOld(linkedList,node)
                print "path: ", path
                return path
            elif currentState in closedSet:
                continue
            else:
                closedSet.add(currentState)
                parentIndex = linkedIndex
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):
                    cumulativeCost = nextCost+heuristicValue(nextState)
                    linkedIndex += 1
                    node = (nextState, nextMove, nextCost, cumulativeCost, linkedIndex, parentIndex)
                    linkedList[linkedIndex] = node
                    if searchtype == 2:
                        fringe.push(nextState,cumulativeCost)
                    else:
                        fringe.push(nextState)

def pathBuilderOld(linkedList, node, tree=[], path=[]):
    """
    (currentState ,currentState,nextState,nextMove,cumulativeCost,nextCost)
    node[-1] is parent node key, node[-2] is current node key, node[-3] is cumulative cost, node[-4] is stepcost, node[1] is the action taken, node[0] is the current state
    """
    if not linkedList[node[-1]] in tree:
        tree.append(linkedList[node[-1]])
        path.append(node[1])
        return pathBuilderOld(linkedList, linkedList[node[-1]], tree, path)
    else:
        path.reverse()
        return path

def genericSearchNew(problem, fringe, searchtype, heuristicValue=(lambda x:0)):
    """
    Generic search method
    """
    gameState = problem.getStartState()
    currentState=gameState
    linkedIndex = 0
    parentIndex = linkedIndex
    node = (currentState, None, 0, 0, 0, 0)
    linkedList = {(linkedIndex):node}
    if problem.isGoalState(currentState):
        return []
    else:
        closedSet=set()
        if searchtype == 2:
            fringe.push(currentState,0+heuristicValue(currentState))
        else:
            fringe.push(currentState)
        while not fringe.isEmpty():
            currentState=fringe.pop()
            if problem.isGoalState(currentState):
                node = (currentState, linkedList[linkedIndex][1], linkedList[linkedIndex][-4], linkedList[linkedIndex][-3], linkedIndex, linkedList[linkedIndex][-1])
                print "node: ", node, "List: ", linkedList
                path = pathBuilderNew(linkedList,node)
                print "path: ", path
                #path.reverse()
                print "revert path: ", path
                return path
            elif currentState in closedSet:
                continue
            else:
                closedSet.add(currentState)
                parentIndex = linkedIndex
                for nextState,nextMove,nextCost in problem.getSuccessors(currentState):
                    cumulativeCost = nextCost+heuristicValue(nextState)
                    linkedIndex += 1
                    node = (nextState, nextMove, nextCost, cumulativeCost, linkedIndex, parentIndex)
                    linkedList[linkedIndex] = node
                    if searchtype == 2:
                        fringe.push(nextState,cumulativeCost)
                    else:
                        fringe.push(nextState)

def pathBuilderNew(linkedList, node, tree=[], path=[]):
    """
    (currentState ,currentState,nextState,nextMove,cumulativeCost,nextCost)
    node[-1] is parent node key, node[-2] is current node key, node[-3] is cumulative cost, node[-4] is stepcost, node[1] is the action taken, node[0] is the current state
    """
    if not linkedList[node[-1]] in tree:
        tree.append(linkedList[node[-1]])
        path.append(node[1])
        return pathBuilderNew(linkedList, linkedList[node[-1]], tree, path)
    else:
        path.reverse()
        return path
    """
    if node[-1] in linkedList:
        parent = linkedList.pop(node[-1])
        if parent[1] <> None:
            tree.append(parent)
            path.append(parent[1])
        return pathBuilderNew(linkedList, parent, tree, path)
    else:
        #path.reverse()
        return path
    """
    """
    if node in linkedList:
        (childList,parent,nextState,action,cumulativeCost,nextCost) = linkedList.pop(node)
        if action <> None:
            path.append(action)
        pathBuilderOld(childList, parent, path)
    else:
        return path
    return path
    """

def depthFirstGenericSearch(problem):
    return genericSearch(problem, util.Stack(), 1, (lambda x: 0));

def breadthFirstGenericSearch(problem):
    return genericSearch(problem, util.Queue(), 1, (lambda x: 0));

def uniformCostGenericSearch(problem):
    return genericSearch(problem, util.PriorityQueue(), 2, (lambda x: 0));

def aStarGenericSearch(problem, heuristic=nullHeuristic):
    return genericSearch(problem, util.PriorityQueue(), 2, (lambda x: heuristic(x,problem))); 

def aStarGenericSearchOld(problem, heuristic=nullHeuristic):
    return genericSearchOld(problem, util.PriorityQueue(), 2, (lambda x: heuristic(x,problem))); 

def aStarGenericSearchNew(problem, heuristic=nullHeuristic):
    return genericSearchNew(problem, util.PriorityQueue(), 2, (lambda x: heuristic(x,problem))); 

# Abbreviations
bfs = breadthFirstSearch
#bfs = breadthFirstGenericSearch
#dfs = depthFirstSearch
dfs = depthFirstGenericSearch
#astar = aStarSearch
astar = aStarGenericSearch
#astar = aStarGenericSearchOld
#astar = aStarGenericSearchNew
#ucs = uniformCostSearch
ucs = uniformCostGenericSearch
